/*
 * Copyright (c) 2008 niels
 *
 * This file is part of BlueRemote. Parts of this file are based 
 * on jRemote (http://sourceforge.net/projects/jremote/).
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * 
 * This program is is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with BlueRemote; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 * 
 */

package BlueRemote;

import java.io.IOException;
import java.util.Vector;

import javax.bluetooth.BluetoothStateException;
import javax.bluetooth.DeviceClass;
import javax.bluetooth.DiscoveryAgent;
import javax.bluetooth.DiscoveryListener;
import javax.bluetooth.LocalDevice;
import javax.bluetooth.RemoteDevice;
import javax.bluetooth.ServiceRecord;
import javax.bluetooth.UUID;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.Displayable;

public class DiscoveryImpl {
    // Bluetooth singleton object
    LocalDevice device;
    DiscoveryAgent agent;
    Main_Midlet _parent;

    // list of discovered devices
    private Vector discoveredDevices = new Vector();
    private Vector deviceNames=new Vector();
    
    // list of DeviceClass discovered (not used in this example)
    public static Vector deviceClasses = new Vector();

    // list of ServiceRecords discovered for one RemoteDevice
    public static Vector services = new Vector();
    
    public DiscoveryImpl(Main_Midlet parent) {
        _parent=parent;
    }
    
    public Vector getDevices() {
        return discoveredDevices;
    }
    
    public Vector getDeviceNames() {
        return deviceNames;
    }

    /**
     * Perform Bluetooth device discovery.
     */
    public void doDiscoverDevice() {
        try {
            // initialize the JABWT stack
            device = LocalDevice.getLocalDevice(); // obtain reference to singleton
            device.setDiscoverable(DiscoveryAgent.GIAC); // set Discover mode to GIAC
            agent = device.getDiscoveryAgent(); // obtain reference to singleton

            // start Bluetooth inquiry (GIAC mode)
            // inquiry response direct to Listener object
            agent.startInquiry(DiscoveryAgent.GIAC, new Listener());

        } catch (BluetoothStateException e) {
            e.printStackTrace();
        }
    }

    /**
     * Perform service discovery on a remote device.
     * @param remote the remote device to inquire services for
     */
    public void doDiscoverService(RemoteDevice remote) {
        try {
            // TODO delete unnecessary attributes
            //
            // this large array of integer values will tell JABWT to query
            // for all known attributes
            // see https://www.bluetooth.org/foundry/assignnumb/document/service_discovery
            // section 4.5 for meaning of these IDs
            //
            // note: you don't have to retrieve all attribute everytime. in fact, you
            // can put null for attr and retrieve just the default values. that probably
            // good enough for most cases. we list all attributes for demo purpose
            //
            // note: For Nokia 6230, there is a limit (13) of number of attribute to retrieve
            // and this large array will cause error. If you are using Nokia 6230, you should
            // reduce this array to 13 elements. Just pick any 13 of them and make sure you pick
            // 0x0001 (ServiceClassID) so we can display the profiel name
            int[] attr = new int[]{0x0000, 0x0001, 0x0002, 0x0003, 0x0004,
                0x0005, 0x0006, 0x0007, 0x0008, 0x0009, 0x000A, 0x000B
            };
            // search for L2CAP services, most services based on L2CAP
            agent.searchServices(attr, // attributes to retrieve from remote device
                    new UUID[]{new UUID(0x0100)}, // search criteria, 0x0100 = L2CAP
                    remote, new Listener()); // direct discovery response to Listener object
        } catch (BluetoothStateException e) {
            e.printStackTrace();

        }

    }

    /**
     *
     * <p>Title: DiscoveryListener implementation that handle discovery response (callback)</p>
     * <p>Description: </p>
     * <p>Copyright: Copyright (c) 2003</p>
     * @author Ben Hui (www.benhui.net)
     * @version 1.0
     */
    class Listener implements DiscoveryListener {

        /**
         * Implements DiscoveryListener interface.
         * This function in invoked for each RemoteDevice discovered by JABWT.
         * See JSR-82 API spec for documentation.
         * @param remoteDevice
         * @param deviceClass
         */
        public void deviceDiscovered(RemoteDevice remoteDevice, DeviceClass deviceClass) {
            //log("A remote Bluetooth device is discovered: " + remoteDevice.getBluetoothAddress().toString());

            // store the device in the list for later use
            discoveredDevices.addElement(remoteDevice);
            deviceClasses.addElement(deviceClass);
        }

        /**
         * Implements DiscoveryListener interface.
         * This function is invoked when the device discovery is completed.
         * See JSR-82 API spec for documentation.
         * @param complete
         */
        public void inquiryCompleted(int complete) {
            // temporary vector to store the sorted devices
            Vector devicesSorted = new Vector();
            
            deviceNames = new Vector();
            int devSize = discoveredDevices.size();

            if (devSize == 0) {
                _parent.notifyEnquiryCompleted(deviceNames);
                return;
            } else if (complete == 0) {
                if (devSize > 0)
                    deviceNames = new Vector();
                
                for (int i = 0; i < devSize; i++) {
                    RemoteDevice rd = (RemoteDevice) discoveredDevices.elementAt(i);
                    try {
                        devicesSorted.addElement(rd);
                        String dname = rd.getFriendlyName(true);
                        if (dname != null) {
                            deviceNames.addElement(dname);
                        }
                    } catch (IOException e) {
                        deviceNames = new Vector();
                        e.printStackTrace();
                    }
                }
                discoveredDevices=devicesSorted;
            }
            
            _parent.notifyEnquiryCompleted(deviceNames);
        }

        /**
         * Implements DiscoveryListener interface.
         * This function is invoked when services are found on a RemoteDevice.
         * See JSR-82 API spec for documentation.
         * @param transId
         * @param records
         */
        public void servicesDiscovered(int transId, ServiceRecord[] records) {
            for (int i = 0; i < records.length; i++) {
                ServiceRecord record = records[i];
                //Util.printServiceRecord( record );
                // store the service records in list for later use
                services.addElement(record);
            }
        }

        /**
         * Implements DiscoveryListener interface.
         * This function is invoked when service discovery is completed on a RemoteDevice.
         * See JSR-82 API spec for documentation.
         * @param transId
         * @param complete
         */
        public void serviceSearchCompleted(int transId, int complete) {
            log("service discovery completed with return code:" + complete);
            log("" + services.size() + " services are discovered");

            if (complete == SERVICE_SEARCH_COMPLETED || complete == SERVICE_SEARCH_NO_RECORDS) {
            // reflect the GUI to show all found services
            //Discovery_MIDlet.instance.serviceDiscoveryUI.showui();
            //Discovery_MIDlet.display.setCurrent(Discovery_MIDlet.instance.serviceDiscoveryUI);
            } else {
            // other possible complete values are
            // SERVICE_SEARCH_DEVICE_NOT_REACHABLE
            // SERVICE_SEARCH_ERROR
            // SERVICE_SEARCH_TERMINATED
            //
            // tell user about the problem
            //Discovery_MIDlet.alert( "Service Discovery imcomplete", Discovery_MIDlet.instance.deviceDiscoveryUI );
            }

        }
    } // Listener

    public void log(String m) {
        //Discovery_MIDlet.log( m );
        //jRemoteBrowse.t.setString(jRemoteBrowse.t.getString() + m);
        System.out.println(m);
    }

    public void commandAction(Command arg0, Displayable arg1) {
    // TODO Auto-generated method stub

    }
}
